//
//  SignInHistoryViewController.m
//  MobileOffice
//
//  Created by jjkj on 16/12/7.
//  Copyright © 2016年 liaoningjujin. All rights reserved.
//

#import "SignInHistoryViewController.h"
#import "SignInHistoryTableViewCell.h"
#import "DateSelectView.h"
#import "SignInHistoryModel.h"
#import "SigninAddressMapViewController.h"
#import "MyImageView.h"

#define getSignRecordList @"getSignRecordList"//签到历史列表

@interface SignInHistoryViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UITableView *_tableView;//列表
    NSInteger _photoPageCount;//当前图片的页数
    NSInteger _photoNum;//照片的总数量
    UIView *_footView;
}
@property (nonatomic,strong) SignInHistoryModel *historyModel;
@end

@implementation SignInHistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setLeftBackNavigation];
    [self setNavigationTitle:@"签到历史"];
    [self creatView];
    [self getSignRecordListRequestWithState:@"0"];
    // Do any additional setup after loading the view.
}

#pragma mark - creatTableView
- (void)creatView{
    self.view.backgroundColor=COLOR_BACKGROUND_GRAY;
    //选择时间的宽度
    CGFloat dateSelectBtnWidth=(IPHONE_WIDTH-6)/2;
    NSArray *dateSelectArr=@[@"选择开始时间",@"选择结束时间"];
    //默认时间为当天
    NSDateFormatter *formatter=[NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *nowTime=[formatter stringFromDate:[NSDate date]];
    self.beginSelectStr=nowTime;
    self.endSelectStr=nowTime;
    for (int i=0; i<dateSelectArr.count; i++) {
        UIButton *signButton=nil;
        signButton=[MyControl creatButtonWithFrame:CGRectMake(2*(i+1)+dateSelectBtnWidth*i,8, dateSelectBtnWidth, 30) target:self sel:@selector(dateSelectButtonClick:) tag:240+i image:nil title:self.beginSelectStr?self.beginSelectStr:dateSelectArr[i]];
        //signButton.backgroundColor=COLOR_BUTTONGREEN;
        [signButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [signButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        signButton.layer.masksToBounds=YES;
        signButton.layer.cornerRadius=5;
        signButton.layer.borderColor=[[UIColor lightGrayColor] CGColor];
        signButton.layer.borderWidth=1;
        [self.view addSubview:signButton];
    }
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 40, IPHONE_WIDTH, IPHONE_HEIGHT-64-40) style:UITableViewStyleGrouped];
    //_myTableView.backgroundColor=[UIColor redColor];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.tag=110;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator=NO;
    _tableView.showsHorizontalScrollIndicator=NO;
    [self addTableViewUpdateRefresh:_tableView BindingIdentity:@""];
    //    [self addTableViewLoadMoreData:_tableView BindingIdentity:@""];
    [self.view addSubview:_tableView];
    
    //    self.definesPresentationContext = YES;
}

#pragma mark -照片查看
- (void)creatPhotoViewWithPhotoUrl:(NSMutableArray *)infoArr index:(NSInteger)index{
    _photoPageCount=0;
    UIButton *photoView=[MyControl creatButtonWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT) target:self sel:@selector(cancelPhotoClick:) tag:200 image:nil title:@""];
    photoView.backgroundColor=[UIColor clearColor];
    [[[UIApplication sharedApplication].delegate window] addSubview:photoView];
    
    //半透明的view
    UIView *alphaView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
    alphaView.backgroundColor=[UIColor blackColor];
    alphaView.alpha=0.5;
    alphaView.userInteractionEnabled=NO;
    [photoView addSubview:alphaView];
    
    _photoNum=infoArr.count;
    //滚动视图
    UIScrollView *scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, (IPHONE_HEIGHT-(IPHONE_WIDTH-40-60))/2, IPHONE_WIDTH, IPHONE_WIDTH-40-60)];
    scrollView.contentSize=CGSizeMake(IPHONE_WIDTH*infoArr.count, 0);
    scrollView.tag=180;
    scrollView.bounces=NO;
    scrollView.userInteractionEnabled=NO;
    scrollView.pagingEnabled=YES;
    scrollView.scrollEnabled=NO;
    [photoView addSubview:scrollView];
    for (int i=0; i<infoArr.count; i++) {
        SignInHistoryModel *imageModel=infoArr[i];
        //照片
        UIImageView *photo=[[UIImageView alloc]initWithFrame:CGRectMake(20+scrollView.width*i, 0, IPHONE_WIDTH-40, scrollView.height)];
        [photo setImageWithURL:[NSURL URLWithString:imageModel.attendPicPath] placeholderImage:[UIImage imageNamed:@"ic_pic_bg@2x"]];
        [scrollView addSubview:photo];
    }
    //如果不止一张图片 则添加向左向右按钮
    UIButton *leftButton=nil;
    UIButton *rightButton=nil;
    if (infoArr.count>1) {
        leftButton=[MyControl creatButtonWithFrame:CGRectMake(5, scrollView.y+(scrollView.height-40)/2, 50, 50) target:self sel:@selector(leftPhotoClick:) tag:220 image:nil title:@""];
        [leftButton setImage:[UIImage imageNamed:@"jiantou_left@2x"] forState:UIControlStateNormal];
        leftButton.layer.masksToBounds=YES;
        leftButton.layer.cornerRadius=leftButton.width/2;
        leftButton.backgroundColor=[UIColor whiteColor];
        leftButton.hidden=YES;
        leftButton.alpha=0.8;
        [photoView addSubview:leftButton];
        
        rightButton=[MyControl creatButtonWithFrame:CGRectMake(IPHONE_WIDTH-5-50,scrollView.y+(scrollView.height-50)/2, 50, 50) target:self sel:@selector(rightPhotoClick:) tag:221 image:nil title:@""];
        rightButton.layer.masksToBounds=YES;
        [rightButton setImage:[UIImage imageNamed:@"jiantou_right@2x"] forState:UIControlStateNormal];
        rightButton.layer.cornerRadius=leftButton.width/2;
        rightButton.backgroundColor=[UIColor whiteColor];
        rightButton.alpha=0.8;
        [photoView addSubview:rightButton];
    }
    scrollView.contentOffset=CGPointMake(IPHONE_WIDTH*index, 0);
    _photoPageCount=index;
    if (_photoPageCount==0) {
        
        leftButton.hidden=YES;
    }else{
        leftButton.hidden=NO;
    }
    if (_photoPageCount==_photoNum-1) {
        rightButton.hidden=YES;
    }else{
        rightButton.hidden=NO;
    }
}

#pragma mark -查看照片向左按钮
- (void)leftPhotoClick:(UIButton *)button{
    _photoPageCount--;
    UIButton *photoButton=(UIButton *)button.superview;
    UIScrollView *scrolleView=(UIScrollView *)[photoButton viewWithTag:180];
    //滚动照片
    scrolleView.contentOffset=CGPointMake(_photoPageCount*IPHONE_WIDTH, 0);
    UIButton *leftButton=(UIButton *)[photoButton viewWithTag:220];
    UIButton *rightButton=(UIButton *)[photoButton viewWithTag:221];
    //    if (_photoPageCount==_photoNum) {
    //        rightButton.hidden=YES;
    //    }else{
    rightButton.hidden=NO;
    //    }
    if (_photoPageCount==0) {
        
        leftButton.hidden=YES;
    }else{
        leftButton.hidden=NO;
    }
}

#pragma mark -查看照片向右按钮
- (void)rightPhotoClick:(UIButton *)button{
    _photoPageCount++;
    UIButton *photoButton=(UIButton *)button.superview;
    UIScrollView *scrolleView=(UIScrollView *)[photoButton viewWithTag:180];
    //滚动照片
    scrolleView.contentOffset=CGPointMake(_photoPageCount*IPHONE_WIDTH, 0);
    UIButton *rightButton=(UIButton *)[photoButton viewWithTag:221];
    UIButton *leftButton=(UIButton *)[photoButton viewWithTag:220];
    //    if (_photoPageCount==0) {
    //        leftButton.hidden=YES;
    //    }else{
    leftButton.hidden=NO;
    //    }
    if (_photoPageCount==_photoNum-1) {
        rightButton.hidden=YES;
    }else{
        rightButton.hidden=NO;
    }
}

#pragma mark -照片查看取消
- (void)cancelPhotoClick:(UIButton *)button{
    [button removeFromSuperview];
}


#pragma mark -时间选择按钮点击
- (void)dateSelectButtonClick:(UIButton *)button{
    [self.view endEditing:YES];
    //日期选择页面
    DateSelectView *datePickerView=[[DateSelectView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)nowDateStr:nil];
    //            __weak UITableView *myTableView=_tableView;
    __weak SignInHistoryViewController *mySelf=self;
    //选择日期后的回调函数
    datePickerView.sureBlock=^(NSString *timeStr){
        //            if (button.tag==250) {
        //                [button setTitle:[timeStr copy] forState:UIControlStateNormal];
        //            }else{
        //                [button setTitle:[timeStr copy] forState:UIControlStateNormal];
        //            }
        [button setTitle:[timeStr copy] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        if (button.tag==240) {
            mySelf.beginSelectStr=[timeStr copy];
        }else{
            mySelf.endSelectStr=[timeStr copy];
        }
        [mySelf getSignRecordListRequestWithState:@"0"];
    };
    [[[UIApplication sharedApplication].delegate window] addSubview:datePickerView];
}

#pragma mark -签到地址点击
- (void)signInAddressClick:(UIButton *)button{
    //取出model
    SignInHistoryModel *model=self.historyModel.dataArr[button.tag-2000];
    //地图详情
    SigninAddressMapViewController *address=[SigninAddressMapViewController new];
    address.addressX=model.SignInlatitude;
    address.addressY=model.SignInlongitude;
    [self.navigationController pushViewController:address animated:YES];
}
#pragma mark -签退地址点击
- (void)signOutAddressClick:(UIButton *)button{
    //取出model
    SignInHistoryModel *model=self.historyModel.dataArr[button.tag-3000];
    //地图详情
    SigninAddressMapViewController *address=[SigninAddressMapViewController new];
    address.addressX=model.SignOutlatitude;
    address.addressY=model.SignOutlongitude;
    [self.navigationController pushViewController:address animated:YES];
}

#pragma mark -照片查看
- (void)imageViewClick:(MyImageView *)imageView{
    SignInHistoryModel *model=self.historyModel.dataArr[imageView.tag-300];
    [self creatPhotoViewWithPhotoUrl:model.attendPhotoList index:imageView.index];
}

#pragma mark -显示照片按钮点击
- (void)photoButtonClick:(UIButton *)button{
    
    SignInHistoryModel *model=self.historyModel.dataArr[button.tag-4000];
    model.isOpen=!model.isOpen;
    button.selected=model.isOpen;
    if (!model.isOpen) {
        _footView.hidden=!model.isOpen;
    }

    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:button.tag-4000]] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - TableViewDelagate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.historyModel.dataArr.count;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellID=@"SignInHistoryTableViewCell";
    SignInHistoryTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell=[[[NSBundle mainBundle]loadNibNamed:@"SignInHistoryTableViewCell" owner:self options:nil]firstObject];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        [cell.signInAddressButton addTarget:self action:@selector(signInAddressClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell.signOutAddressButton addTarget:self action:@selector(signOutAddressClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell.photoButton addTarget:self action:@selector(photoButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    cell.signInAddressButton.tag=2000+indexPath.section;
    cell.signOutAddressButton.tag=3000+indexPath.section;
    cell.photoButton.tag=4000+indexPath.section;
    _footView=cell.footView;
    SignInHistoryModel *model=self.historyModel.dataArr[indexPath.section];
    //填充cell
    cell.nameLabel.text=[NSString stringWithFormat:@"%@    %@",model.empName,[LZXHelper getTimeStrWithOldDateFomatter:@"yyyy-MM-dd HH:mm" DateStr:model.signInTime newFormatter:@"yyyy-MM-dd"]];
    [cell.signInAddressButton setTitle:[NSString stringWithFormat:@"签到：%@",model.signInAddress] forState:UIControlStateNormal];
    [cell.signOutAddressButton setTitle:[NSString stringWithFormat:@"签退：%@",model.signOutAddress] forState:UIControlStateNormal];
    cell.signInDateLabel.text=[NSString stringWithFormat:@"签到：%@    签退：%@",[LZXHelper getTimeStrWithOldDateFomatter:@"yyyy-MM-dd HH:mm" DateStr:model.signInTime newFormatter:@"HH:mm"],[LZXHelper getTimeStrWithOldDateFomatter:@"yyyy-MM-dd HH:mm" DateStr:model.signOutTime newFormatter:@"HH:mm"]];
    if (model.attendPhotoList!=nil&&model.attendPhotoList.count>0) {
        cell.photoButton.hidden=NO;
    }else{
        cell.photoButton.hidden=YES;
    }
    //如果有照片则显示照片
    if (model.attendPhotoList!=nil&&model.attendPhotoList.count>0&&model.isOpen==YES) {
        cell.footView.hidden=NO;
        //先移除上面的视图
        [cell.footView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        for (int i=0; i<model.attendPhotoList.count; i++) {
            SignInHistoryModel *imageModel=model.attendPhotoList[i];
            //签到拍照时间
            UILabel *titleLabel=[MyControl creatLabelWithFrame:CGRectMake(8, 8*(i+1)+150*i, 80, 20) text:[LZXHelper getTimeStrWithOldDateFomatter:@"yyyy/MM/dd HH:mm:ss" DateStr:imageModel.createTime newFormatter:@"HH:MM"]];
            titleLabel.textColor=[UIColor lightGrayColor];
            titleLabel.textAlignment=NSTextAlignmentCenter;
            [cell.footView addSubview:titleLabel];
            //照片
            MyImageView *imageView=[[MyImageView alloc]initWithFrame:CGRectMake(titleLabel.x+titleLabel.width+20, titleLabel.y, 100, 150)];
            imageView.tag=300+indexPath.section;
            [imageView addTarget:self action:@selector(imageViewClick:)];
            imageView.index=i;
            [imageView setImageWithURL:[NSURL URLWithString:imageModel.attendPicPath] placeholderImage:[UIImage imageNamed:@"ic_pic_bg@2x"]];
            [cell.footView addSubview:imageView];
        }
        cell.footView.height=model.attendPhotoList.count*166;
    }else{
        cell.footView.hidden=YES;
        cell.footView.height=0;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SignInHistoryModel *model=self.historyModel.dataArr[indexPath.section];
    CGFloat height=model.attendPhotoList.count*166*(model.isOpen?1:0);
    return 111+height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

#pragma mark -刷新
- (void)loadUpdateRefreshWithBindingIdentity:(NSString *)BindingIdentity{
    _isRefresh=YES;
    //取出第一个model的id
    if (self.historyModel.dataArr.count>0) {
        SignInHistoryModel *model=[self.historyModel.dataArr firstObject];
        _pageNum=model.ids;
    }
    [self getSignRecordListRequestWithState:@"2"];
}
#pragma mark -加载更多
- (void)loadMoreDataWithBindingIdentity:(NSString *)BindingIdentity{
    _isLoadMore=YES;
    //取出最后一个model的id
    if (self.historyModel.dataArr.count>0) {
        SignInHistoryModel *model=[self.historyModel.dataArr lastObject];
        _pageNum=model.ids;
    }
    [self getSignRecordListRequestWithState:@"1"];
}


#pragma mark -签到历史列表
- (void)getSignRecordListRequestWithState:(NSString *)state{
    NSDictionary *dict=@{
                         @"beginTime":self.beginSelectStr?self.beginSelectStr:@"",
                         @"endTIme":self.endSelectStr?self.endSelectStr:@"",
                         @"conditionWord":@"",
                         @"fid":_pageNum?_pageNum:@"0",
                         @"khswitchId":@"",
                         @"state":state,
                         @"userType":[LZXHelper getUserType],
                         };
    
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",_empids?_empids:[LZXHelper getSessionID],str];
    // __weak AddressBookViewController *mySelf=self;
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:getSignRecordList soapBody:soap success:^(id responseObject) {
        [LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
        SignInHistoryModel *model=[[SignInHistoryModel alloc]initWithResponse:responseObject];
        if ([model.code isEqualToString:@"200"]) {
            //刷新的时候
            if (_isRefresh) {
                //将新数据插入到列表中
                if (model.dataArr.count>0) {
                    [self.historyModel.dataArr insertObjects:model.dataArr atIndexes:[NSIndexSet indexSetWithIndex:0]];
                }
                [self endRefreshWithTableView:_tableView];
                //加载更多
            }else if (_isLoadMore){
                for (int i=0;i<model.dataArr.count ; i++) {
                    SignInHistoryModel *newModel=model.dataArr[i];
                    [self.historyModel.dataArr addObject:newModel];
                }
                [self endRefreshWithTableView:_tableView];
                //第一次加载
            }else{
                self.historyModel=model;
                if (!(self.historyModel.dataArr.count<10)) {
                    [self addTableViewLoadMoreData:_tableView BindingIdentity:@""];
                }
            }
            if (self.historyModel.dataArr.count==0) {
                [self addReminderViewWithFrame:_tableView.frame msg:@"当前查询条件下暂时没有信息~" backView:self.view];
            }else{
                [self removeReminderView];
            }
            [_tableView reloadData];
        }else if([model.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:model.msg View:[[UIApplication sharedApplication].delegate window]];
        }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:self.view];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
